JavaScript eval() with `this`

Posted by mojuba on Stack Overflow See other posts from Stack Overflow or by mojuba
Published on 2012-09-30T20:44:37Z Indexed on 2012/09/30 21:37 UTC
Read the original article Hit count: 184

Filed under:
|

If I define a JavaScript code snippet in my HTML, like so:

<div id=myElem onMyUpdate="alert('Update called for ' + this.id)">...

then what is the most elegant way of evaluating it from within JavaScript with this properly assigned?

What I came up with so far is something like this:

if (elem.hasAttribute('onMyUpdate'))
    (function () { eval(elem.getAttribute('onMyUpdate')) }).call(elem);

which looks terrible (to me), but works. Any better/more elegant alternatives?

MDN says there used to be the second argument to eval() for doing just that but it's deprecated now; MDN then suggests to use operator with() instead, which, if you follow the link provided, turns out to be made deprecated by the latest standard. Dead end, in other words.

(As a side note, StackOverflow ignores the word this in search terms and thus it may miss relevant answers - is there a way of telling it not to?)

Edit: I forgot to mention: no jQuery please, just vanilla JavaScript

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about eval